<template>
  <div
    class="plan-edit-box"
    element-loading-text="数据加载中"
    element-loading-spinner="el-icon-loading"
    v-loading="pageLoading"
  >
    <div class="plan-page-header">
      <div class="header-title">{{ title }}</div>
      <div class="header-btns">
        <RPButton optType="reset" style="margin-right: 10px" @click="hideFun" text="取消" />
        <RPButton v-if="!disabledPage" style="margin-right: 10px" :loading="createLoadding" optType="create" type="info" @click="save('save')" text="保存" />
        <RPButton v-if="!disabledPage" :loading="createLoadding" optType="create" type="info" @click="save('saveAndSubmit')" text="保存并提交" />
      </div>
    </div>
    <div class="plan-page-content">
      <Form
        :model="modelForm"
        :disabled="disabledPage"
        ref="editForm"
        class="ivu-form-no-margin-bottom"
        :rules="rule"
        :label-width="140"
      >
        <Row :gutter="20" class="code-row-bg">
          <Col span="12" style="border: none">
            <Form-item class="ivu-form-item ivu-form-item-required" prop="ruleGroupName" label="规则组名称：">
              <Input v-model="modelForm.ruleGroupName" :maxlength="20" placeholder="请输入" />
            </Form-item>
          </Col>
          <Col span="12" style="border: none">
            <Form-item class="ivu-form-item" prop="description" label="规则组描述：">
              <Input v-model="modelForm.description" :maxlength="100" placeholder="请输入" />
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="12" style="border: none">
            <Form-item prop="reportType" label="类型：">
              <Select v-model="modelForm.reportType">
                <Option
                  v-for="item in reportTypeList"
                  :value="item.vsiValue"
                  :key="item.vsiValue"
                  >{{ item.vsiValue }}</Option
                >
              </Select>
            </Form-item>
          </Col>
          <Col span="12" style="border: none">
            <Form-item prop="reportName" label="领域：">
              <Select v-if="showReportName" v-model="modelForm.reportNameCopy" @on-change="reportChange">
                <Option
                  v-for="item in reportNameList"
                  :value="item.vsiValue"
                  :key="item.vsiValue"
                  >{{ item.vsiValue }}</Option
                >
              </Select>
            </Form-item>
          </Col>
        </Row>
        <Row :gutter="20" class="code-row-bg">
          <Col span="21" style="border: none">
            <Row :gutter="18" v-for="(item, index) in modelForm.remindRuleVoList" :key="index" class="code-row-bg" style="background-color: #f9f9f9; padding: 15px; display: block;margin-left:5px">
              <div style=" margin-bottom: 10px">
                <span style="font-size:18px;">规则{{ index + 1 }}</span>
                <Button type="text" style="padding:0; float: right" icon="ios-trash-outline" v-if='modelForm.remindRuleVoList.length > 1' @click="deleteRule(index, item)"/>
              </div>
              <div style="background-color: #fff; padding: 10px">
                <Row :gutter="20" class="code-row-bg">
                  <Col span="12" style="border: none">
                    <Form-item class="ivu-form-item ivu-form-item-required" 
                    :prop="'remindRuleVoList.'+index+'.triggerCondition'" 
                    label="触发条件："
                    :rules="ruleReport.triggerCondition">
                      <Select v-model="item.triggerCondition" :disabled="item.editFlag == '0'" @on-change="triggerChanged(index)">
                        <Option
                          v-for="item2 in triggerConditionList"
                          :value="item2.value"
                          :key="item2.value"
                          >{{ item2.text }}</Option>
                      </Select>
                    </Form-item>
                  </Col>
                  <Col span="12" style="border: none">
                    <Form-item class="ivu-form-item ivu-form-item-required" 
                    :prop="'remindRuleVoList.'+index+'.triggerTime'" 
                    label="触发时间："
                    :rules="item.editFlag !== '0' ? ruleReport.triggerTime : []">
                      <DatePicker
                        v-model="item.triggerDate"
                        :disabled="item.editFlag == '0'"
                        type="datetime"
                        :editable="false"
                        placeholder="请选择触发时间"
                        @on-change="val => changeTriggerTime(val, index)"
                      />
                    </Form-item>
                  </Col>
                </Row>
                <Row :gutter="20" class="code-row-bg" v-if="[3,4].indexOf(item.triggerCondition) >= 0 && modelForm.reportType == '专项工作' && ['数字化转型专项实施方案任务表'].findIndex(name => name == modelForm.reportName) !== -1">
                  <Col span="12" style="border: none" v-if="item.triggerCondition === 3">
                    <Form-item class="ivu-form-item ivu-form-item-required" 
                    :prop="'remindRuleVoList.'+index+'.scheduledDate'" 
                    label="计划填报时间："
                    :rules="ruleReport.scheduledDate">
                      <DatePicker
                        v-model="item.scheduledDate"
                        :disabled="item.editFlag == '0'"
                        type="date"
                        :editable="false"
                        placeholder="请选择计划填报时间"
                        @on-change="val => changeTime(val, 'scheduledTime', index)"
                      />
                    </Form-item>
                  </Col>
                  <Col span="12" style="border: none" v-else>
                    <Form-item class="ivu-form-item ivu-form-item-required" 
                    :prop="'remindRuleVoList.'+index+'.scheduledDate'" 
                    label="计划截止时间："
                    :rules="ruleReport.scheduledDate">
                      <DatePicker
                        v-model="item.scheduledDate"
                        :disabled="item.editFlag == '0'"
                        type="date"
                        :editable="false"
                        placeholder="请选择计划截止时间"
                        @on-change="val => changeTime(val, 'scheduledTime', index)"
                      />
                    </Form-item>
                  </Col>
                </Row>
                <Row v-if="showYearOrQuarter(item)" :gutter="20" class="code-row-bg">
                  <Col span="12" style="border:none;">
                  <Form-item :prop="'remindRuleVoList.'+index+'.reportYear'" :label="yearOrQuarterLable" :rules="ruleReport.reportYear">
                      <!-- <DatePicker type="year" v-model="item.reportYear" :options="optionss"  placeholder="请选择年份" /> -->
                      <Select  v-model="item.reportYear" :disabled="item.editFlag == '0'">
                        <Option v-for="item2 in yearOptions" :value="item2.value" :key="item2.value">{{ item2.text }}</Option>
                      </Select>
                    </Form-item>
                  <!-- <div class="Selecequarters" >
                  </div> -->
                  </Col>
                  <!-- <Col span="1">
                    <span v-if="modelForm.reportName == '数字化转型专项实施方案任务表'" style="margin:10px; margin-left: -590px;margin-right:-130px">-</span>
                  </Col> -->
                  <Col span="12" style="display: flex">
                    <span v-if="modelForm.reportName == '数字化转型专项实施方案任务表'" style="margin: 5px;margin-right: 20px;">-</span>
                    <Form-item v-if="modelForm.reportName == '数字化转型专项实施方案任务表'" 
                      :prop="'remindRuleVoList.'+index+'.reportQuarter'"
                      :rules="ruleReport.reportQuarter" :label-width="0">
                      <Select v-model="item.reportQuarter" :disabled="item.editFlag == '0'" placeholder="请选择季度">
                        <Option  v-for="item2 in datasList" :key="item2.key" :value="item2.value">{{item2.value}}</Option>
                      </Select>
                    </Form-item >
                  </Col>
                </Row>
                <Row :gutter="20" class="code-row-bg">
                  <Col span="24" style="border: none">
                    <Form-item class="ivu-form-item ivu-form-item-required" 
                    :prop="'remindRuleVoList.'+index+'.receiveWay'" 
                    label="接收方式："
                    :rules="ruleReport.receiveWay">
                      <CheckboxGroup v-model="item.receiveWayArr" @on-change="val => changeReceiveWay(val, index)">
                        <Checkbox
                          v-for="item2 in receiveWayList"
                          :disabled="item.editFlag == '0'"
                          :label="item2.value"
                          :key="item2.value"
                        >{{ item2.text }}</Checkbox>
                      </CheckboxGroup>
                    </Form-item>
                  </Col>
                </Row>
                <Row :gutter="20" class="code-row-bg">
                  <Col span="24" style="border: none">
                    <Form-item :required="true" label="接收人：">
                      <RadioGroup v-model="item.receiveType" @on-change="val => receiveTypeChange(val, index)">
                        <Radio
                          v-for="item2 in receiveTypeList"
                          :disabled="item.editFlag == '0'"
                          :label="item2.value"
                          :key="item2.value"
                        >{{ item2.text }}</Radio>
                      </RadioGroup>
                    </Form-item>
                  </Col>
                </Row>
                <Row :gutter="20" class="code-row-bg">
                  <Col span="20" style="border: none">
                      <Form-item :prop="'remindRuleVoList.'+index+'.receivers'" :rules="(item.receiverNames == '收件人组已删除' && !disabledPage && item.editFlag == '1') || action == 'create' ? ruleReport.receivers : []">
                        <div class="user-list">
                            <div class="user" v-for="(item2, index2) in item.receiverList" :key="index2">
                              <span class="user-name">{{item2.name}}</span>
                              <Icon v-show="(!disabledPage && item.editFlag == '1') || action == 'create'" type="ios-close" @click="removeUser(item2, index)"/>
                            </div>
                        </div>
                        <Input v-show="false" v-model="item.receivers" type="textarea" :rows="4" placeholder="请输入" />
                      </Form-item>
                  </Col>
                  <Col span="4" style="border: none">
                    <RPButton v-if="(action == 'edit' && item.editFlag == '1')
                        || action == 'edit' && item.source != 'database'
                        || action == 'create'" class="button" optType="create" text="选择" @click="selectAddress(index)"></RPButton>
                  </Col>
                </Row>
                <Row :gutter="20" class="code-row-bg">
                  <Col span="24" style="border: none">
                    <Form-item class="ivu-form-item ivu-form-item-required" 
                    :prop="'remindRuleVoList.'+index+'.mailTitle'" label="邮件主题：" 
                    :rules="ruleReport.mailTitle">
                      <Input v-model="item.mailTitle" :disabled="item.editFlag == '0'" :maxlength="50" placeholder="请输入" />
                    </Form-item>
                  </Col>
                </Row>
                <Row :gutter="20" class="code-row-bg">
                  <Col span="24" style="border: none">
                    <Form-item :prop="'remindRuleVoList.'+index+'.context'" label="邮件内容：" :rules="ruleReport.context">
                      <Input v-model="item.context" :disabled="item.editFlag == '0'" :maxlength="2000" type="textarea" :rows="4" placeholder="请输入" />
                    </Form-item>
                  </Col>
                </Row>
              </div>
            </Row>
          </Col>
          <Col span="3" style="border: none">
            <RPButton optType="create" @click="createRule" v-if="action !== 'detail'"/>
          </Col>
        </Row>
      </Form>
    </div>
  </div>
</template>
<script>
import ruleConfigApi from '@/api/ruleConfig.js'
import coverApi from '@/api/cover.js'
import SeleceAddressDatas from '../SeleceAddressDatas.vue'
import selectGroup from '../selectGroup.vue'
import selectGroupByTable from '../selectGroupByTable.vue'
import editRuleConfigConfirm from './editRuleConfigConfirm.vue'
import { 
  TRIGGER_CONDITION_LIST,
  TRIGGER_CONDITION_NOT_SUBMIT,
  TRIGGER_CONDITION_NOT_DELAY,
  RECEIVE_WAY_LIST,
  REMIND_WAY_EMAIL,
  RECEIVE_TYPE_LIST,
  RECEIVE_TYPE_PERSON,
  TRIGGER_CONDITION_START,
  TRIGGER_CONDITION_URGING,
  ACTION_BUTTON_SAVE,
  ACTION_BUTTON_SAVE_AND_SUBMIT,
} from '../const.js'
let defaultValue = {
  triggerCondition: '', // 0-未提交, 1-未更新
  reportYear: '',
  reportQuarter: '',
  triggerTime: '',
  triggerDate: '',
  receiveWay: `${REMIND_WAY_EMAIL}`, // 0-邮件, 1-润工作, 多选以逗号分割
  receiveType: RECEIVE_TYPE_PERSON, // 0-收件人, 1-收件人组
  receivers: '',
  mailTitle: '',
  context: '',
  scheduledDate: '',
  scheduledTime: '',
  receiverList: [],
  receiveWayArr: [REMIND_WAY_EMAIL],
}
// 规则是否可编辑--是
const RULE_EDITEBLE_FLAG_YES = '1'
// 规则是否可编辑--否
const RULE_EDITEBLE_FLAG_NO = '0'
export default {
  components: {},
  name: 'createConfig',
  props: {
    disabledPage: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default() {
        return ''
      }
    },
    id: {
        type: String,
        default: ''
    },
    action: {
        type: String,
        default: 'create'
    },
  },
  data() {
    const validatorRuleName =  (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入规则组名称'))
      }else {
        callback()
      }
    }
    const validatormailTitle =  (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入邮件主题'))
      }else {
        callback()
      }
      //  else if (!/^([\u4e00-\u9fa5A-Za-z]){2,64}$/.test(value)) {
      //   callback(new Error('规则名称仅支持中文、英文，2-64个字符'))
      // } 
    }
    const validatorTriggerTime =  (rule, value, callback) => {
      if (this.disabledPage) {
        callback()
      } else {
        if (!value) {
          callback(new Error('请选择触发时间'))
        } else if (Date.now() > new Date(value).valueOf()) {
          callback(new Error('触发时间必须选择未来的时间'))
        } else {
          callback()
        }
      }
    }
    const validatorscheduledDate = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择时间'))
      } else {
        callback()
      }
    }
    const validatorTriggerCondition = (rule, value, callback) => {
      if (!value && value !== TRIGGER_CONDITION_NOT_SUBMIT) {
        callback(new Error('请选择触发条件'))
      } else {
        callback()
      }
    }
    const validatorReportYear = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择年度'))
      } else {
        callback()
      }
    }
    const validatorReportQuarter = (rule, value, callback) => {
      if (!value && this.modelForm.reportName == '数字化转型专项实施方案任务表') {
        callback(new Error('请选择季度'))
      } else {
        callback()
      }
    }
    const validatorReceiveWay = (rule, value, callback) => {
      if (!value && value !== `${REMIND_WAY_EMAIL}`) {
        callback(new Error('请选择接收方式'))
      } else {
        callback()
      }
    }
    return {
      datasList:[
          {key:'0',value:'1'},
          {key:'1',value:'2'},
          {key:'2',value:'3'},
          {key:'3',value:'4'},
      ],
      optionss:{
        disabledDate(date){
          // const disabledDate = date.getFullYear()
          // return ( disabledDate > 2025 || disabledDate < 2021 )
          // 先不做控制
          return false
        }
      },
      yearOptions: [
              {text: '2021', value: '2021'},
              {text: '2022', value: '2022'},
              {text: '2023', value: '2023'},
              {text: '2024', value: '2024'},
              {text: '2025', value: '2025'}
            ],
      pageLoading: false,
      createLoadding: false,
      reportTypeList: [
      ],
      // allReportNameList: {
      //   '专项工作': [
      //     {text: '关键业务环节数字化覆盖度', value: '关键业务环节数字化覆盖度'},
      //     {text: '数字化转型专项实施方案任务表', value: '数字化转型专项实施方案任务表'}
      //   ]
      // },
      allReportNameList: [],
      reportNameList: [],
      triggerConditionList: [],
      receiveWayList: RECEIVE_WAY_LIST,
      receiveWayArr: [REMIND_WAY_EMAIL],
      receiveTypeList: RECEIVE_TYPE_LIST,
      receiverList: [],
      showReportName: true,
      modelForm: {
        id: '',
        ruleGroupName: '',
        description: '',
        reportType: '',
        reportTypeCode: '',
        reportName: '',
        reportCode: '',
        reportNameCopy: '',
        remindRuleVoList: [
          {
            triggerCondition: '', // 0-未提交, 1-未更新
            reportYear: '',
            reportQuarter: '',
            triggerTime: '',
            receiveWay: `${REMIND_WAY_EMAIL}`, // 0-邮件, 1-润工作, 多选以逗号分割
            receiveType: RECEIVE_TYPE_PERSON, // 0-收件人, 1-收件人组
            receivers: '',
            mailTitle: '',

            context: '',
            receiverList: [],
            receiveWayArr: [REMIND_WAY_EMAIL],
            userWithTrgNode: [],
          }
        ],
        
      },
      rule: {
        ruleGroupName: [{ required: false, validator: validatorRuleName.bind(this), trigger: 'blur' }],
        reportType: [{ required: true, message: '请选择类型', trigger: 'blur' }],
        reportName: [{ required: true, message: '请选择领域', trigger: 'blur' }],
      },
      ruleReport:{
        triggerCondition: [{ required: false, validator: validatorTriggerCondition.bind(this), trigger: 'change' }],
        reportYear: [{ required: true, validator: validatorReportYear.bind(this), trigger: 'change' }],
        reportQuarter: [{ required: true, validator: validatorReportQuarter.bind(this), trigger: "change" }],
        triggerTime: [{ required: false, validator: validatorTriggerTime.bind(this), trigger: 'change' }],
        receiveWay: [{ required: false, validator: validatorReceiveWay.bind(this), trigger: 'change' }],
        receivers: [{ required: true, message: '请选择接收人', trigger: 'blur' }],
        mailTitle: [{ required: false, validator: validatormailTitle.bind(this), trigger: 'blur' }],
        context: [{ required: true, message: '请输入邮件内容', trigger: 'blur' }],
        scheduledDate: [{ required: true, validator: validatorscheduledDate.bind(this), trigger: 'change' }],
      },
      triggerTimeOption:{
        disabledDate(date){
          return date && (date.valueOf() + 24 * 60 * 60 * 1000) < Date.now()
        }
      },
      initLoading: false,
      allUser: []
    }
  },
  computed: {
    yearOrQuarterLable() {
      return this.modelForm.reportName == '关键业务环节数字化覆盖度' ? '年度：' : '季度：'
    },
  },
  async created() {
    if (this.id) {
      this.pageLoading = true
    }
    await Promise.all([this.getUserList(), coverApi.getCodeManage(
        {
          commonPageDTO: { currentPage: 1, pageSize: 10 },
          condition: { tenantCode: 'IT_SHARE_DEVELOP', vsCode: 'REPORT_FORM_TYPE' },
          pageNum: 1,
          pageSize: 10,
          sortDTO: { fieldName: '', orderBy: '' },
          tenantCode: 'IT_SHARE_DEVELOP',
          vsCode: 'REPORT_FORM_TYPE'
        }
      ).then(res => {
      this.reportTypeList = res.data.records
    }), coverApi.getCodeManage(
      {
        commonPageDTO: { currentPage: 1, pageSize: 10 },
        condition: { tenantCode: 'IT_SHARE_DEVELOP', vsCode: 'REPORT_FORMS' },
        pageNum: 1,
        pageSize: 10,
        sortDTO: { fieldName: '', orderBy: '' },
        tenantCode: 'IT_SHARE_DEVELOP',
        vsCode: 'REPORT_FORMS'
      }
    ).then(res => {
      this.allreportNameList = res.data.records
    })])
    // await this.getUserList()
    // await coverApi.getCodeManage(
    //     {
    //       commonPageDTO: { currentPage: 1, pageSize: 10 },
    //       condition: { tenantCode: 'IT_SHARE_DEVELOP', vsCode: 'REPORT_FORM_TYPE' },
    //       pageNum: 1,
    //       pageSize: 10,
    //       sortDTO: { fieldName: '', orderBy: '' },
    //       tenantCode: 'IT_SHARE_DEVELOP',
    //       vsCode: 'REPORT_FORM_TYPE'
    //     }
    //   ).then(res => {
    //   this.reportTypeList = res.data.records
    // })
    // await coverApi.getCodeManage(
    //   {
    //     commonPageDTO: { currentPage: 1, pageSize: 10 },
    //     condition: { tenantCode: 'IT_SHARE_DEVELOP', vsCode: 'REPORT_FORMS' },
    //     pageNum: 1,
    //     pageSize: 10,
    //     sortDTO: { fieldName: '', orderBy: '' },
    //     tenantCode: 'IT_SHARE_DEVELOP',
    //     vsCode: 'REPORT_FORMS'
    //   }
    // ).then(res => {
    //   this.allreportNameList = res.data.records
    // })
    this.getDetail()
  },
  watch: {
    'modelForm.reportType': {
      handler(val) {
        let selectCode = val ? this.reportTypeList.find(item => item.vsiValue == val).vsiKey : ''
        this.reportNameList = val ? this.allreportNameList.filter(item => item.vsiParentKey == selectCode) : [];
        if (!this.initLoading) {
          this.modelForm.reportCode = ''
        }
      },
      immediate: true
    },
    'modelForm.reportName': {
      handler(val) {
        // this.$set(this.modelForm, 'triggerCondition', '')
        // this.$set(this.modelForm, 'context', '')
        let selectData = this.reportNameList.find(item => item.vsiValue == val)
        if (selectData) {
          let list = JSON.parse(selectData.vsiDescription.slice(1,-1)) || []
          this.triggerConditionList = list
        }
        // this.setTriggerConditionList()
      }
    },
  },
  beforeMount: function () {},
  mounted() {},
  beforeDestroy: function () {},
  destroyed: function () {},
  methods: {
    getUserList() {
      return coverApi.getRptTrgnodeTree({
          parentNodeCode: -1,
        }).then(res => {
          let data = res.data.data
          this.allUser = data
        })
    },

    reportChange(data) {
      if (this.modelForm.reportName && (this.modelForm.remindRuleVoList.length > 1 || this.getValue(this.modelForm.remindRuleVoList))) {
        this.modelForm.reportNameCopy = this.modelForm.reportName
        this.$confirm({
          title:"切换领域",
          content: "切换领域将会重置规则，您确认要继续吗?"
        }).then(()=>{
          this.modelForm.reportName = data
          this.modelForm.reportNameCopy = data
          this.modelForm.remindRuleVoList = [
            {
              triggerCondition: '', // 0-未提交, 1-未更新
              reportYear: '',
              reportQuarter: '',
              triggerTime: '',
              receiveWay: `${REMIND_WAY_EMAIL}`, // 0-邮件, 1-润工作, 多选以逗号分割
              receiveType: RECEIVE_TYPE_PERSON, // 0-收件人, 1-收件人组
              receivers: '',
              mailTitle: '',
              context: '',
              receiverList: [],
              receiveWayArr: [REMIND_WAY_EMAIL],
              userWithTrgNode: [],
            }
          ]
          this.$nextTick(() => {
            this.reportNameChange()
          })
        }).catch(() => {
          this.showReportName = false
          this.modelForm.reportNameCopy = this.modelForm.reportName
          setTimeout(() => {
            this.showReportName = true
          })
        })
      } else {
        this.modelForm.reportName = data
      }

    },
    getValue(list) {
      let flag = false
      list.forEach(item => {
        for(let key in item) {
          if (key == 'receiverList' && item[key].length > 0) {
             flag = true
          } else if (key == 'receiveWayArr' && (item[key].length != 1 || (item[key].length == 1 && item[key][0] !== REMIND_WAY_EMAIL))) {
            flag = true
          } else if (key != 'receiverList' && key != 'receiveWayArr' && item[key] != defaultValue[key] && item[key] != undefined) {
            flag = true
          }
        }
      })
      return flag
    },
    createRule() {
      this.modelForm.remindRuleVoList.push({
        triggerCondition: '', // 0-未提交, 1-未更新
        reportYear: '',
        reportQuarter: '',
        triggerTime: '',
        receiveWay: `${REMIND_WAY_EMAIL}`, // 0-邮件, 1-润工作, 多选以逗号分割
        receiveType: RECEIVE_TYPE_PERSON, // 0-收件人, 1-收件人组
        receivers: '',
        mailTitle: '',
        context: '',
        receiverList: [],
        receiveWayArr: [REMIND_WAY_EMAIL],
        userWithTrgNode: [],
      })
    },
    deleteRule(index, item) {
      if (this.modelForm.remindRuleVoList.length > 1) {
        if (item.editFlag == '0') {
          this.$confirm({
            title: '',
            content: '该规则已执行，删除后将无记录，您确认要删除吗？'
          }).then(()=>{
            this.modelForm.remindRuleVoList.splice(index, 1)
          })
        } else {
          this.modelForm.remindRuleVoList.splice(index, 1)
        }
      }
    },
    showYearOrQuarter(item) {
      // return this.modelForm.reportName && item.triggerCondition != TRIGGER_CONDITION_NOT_DELAY
      return this.modelForm.reportName && [0, 3, 4].findIndex(code => code == item.triggerCondition) !== -1 && this.modelForm.reportType == '专项工作' && ['数字化转型专项实施方案任务表'].findIndex(name => name == this.modelForm.reportName) !== -1
    },
    reportNameChange() {
      for (const key in this.modelForm.remindRuleVoList) {
        if (Object.hasOwnProperty.call(this.modelForm.remindRuleVoList, key)) {
          const element = this.modelForm.remindRuleVoList[key];
          this.$set(element, 'triggerCondition', '')
          this.$set(element, 'context', '')    
        }
      }
    },
    setTriggerConditionList() {
      let reportName = this.modelForm.reportName
      if (reportName == '数字化转型专项实施方案任务表') {
        this.triggerConditionList = TRIGGER_CONDITION_LIST
      } else if (reportName == '关键业务环节数字化覆盖度') {
        this.triggerConditionList = TRIGGER_CONDITION_LIST.filter(item => item.value !== TRIGGER_CONDITION_NOT_DELAY)
      }
    },
    triggerChanged(index) {
      this.setRemindContext(index)
    },
    setRemindContext(index) {
      let triggerCondition = this.modelForm.remindRuleVoList[index].triggerCondition
      let reportName = this.modelForm.reportName
      if (reportName == '数字化转型专项实施方案任务表') {
        if (triggerCondition === TRIGGER_CONDITION_NOT_DELAY) {
          this.$set(this.modelForm.remindRuleVoList[index], 'context', '{BU}，截止至{time}系统检测到贵单位提交的{report name}中有已延期任务项，请关注！')
        } else if (triggerCondition === TRIGGER_CONDITION_NOT_SUBMIT) {
          this.$set(this.modelForm.remindRuleVoList[index], 'context', '{BU}，截止至{time}系统检测到贵单位仍未提交/更新{filling time}季度{report name}，请及时处理！')
        } else if (triggerCondition === TRIGGER_CONDITION_START) {
          this.$set(this.modelForm.remindRuleVoList[index], 'context', '{BU}，数字化转型实施方案任务表{filling time}季度管理已于{scheduled time}启动更新，请及时处理！')
        } else if (triggerCondition === TRIGGER_CONDITION_URGING) {
          this.$set(this.modelForm.remindRuleVoList[index], 'context', '{BU}，数字化转型实施方案任务表{filling time}季度管理将在{deadline}停止更新，届时系统将关闭，贵单位尚存未提交表单，请关注！')
        }
      } else if (reportName == '关键业务环节数字化覆盖度') {
        if (triggerCondition === TRIGGER_CONDITION_NOT_SUBMIT) {
          this.$set(this.modelForm.remindRuleVoList[index], 'context', '{username}您好，截止至{time}系统检测到您仍未提交{filling time}年度{report name}，请及时提交！')
        } else if (triggerCondition === TRIGGER_CONDITION_START) {
          this.$set(this.modelForm.remindRuleVoList[index], 'context', '{BU}，关键业务环节数字化覆盖度{filling time}季度管理已于{scheduled time}启动更新，请及时处理！')
        } else if (triggerCondition === TRIGGER_CONDITION_URGING) {
          this.$set(this.modelForm.remindRuleVoList[index], 'context', '{BU}，关键业务环节数字化覆盖度{filling time}季度管理将在{deadline}停止更新，届时系统将关闭，贵单位尚存未提交表单，请关注！')
        }
      } else {
        this.$set(this.modelForm.remindRuleVoList[index], 'context', '')
      }
      if (this.modelForm.remindRuleVoList[index].receiveType != RECEIVE_TYPE_PERSON) {
        this.replaceContent(index)
      }
    },
    removeUser(item, index) {
      this.modelForm.remindRuleVoList[index].receiverList = this.modelForm.remindRuleVoList[index].receiverList.filter((user) => user.id !== item.id)
      let idList = this.modelForm.remindRuleVoList[index].receiverList.map(item => item.id)
      this.modelForm.remindRuleVoList[index].receivers = idList.length ? idList.join(',') : ''
      if(this.modelForm.remindRuleVoList[index].receiveType == RECEIVE_TYPE_PERSON) {
        this.modelForm.remindRuleVoList[index].userWithTrgNode = this.modelForm.remindRuleVoList[index].userWithTrgNode.filter(user => user.name != item.name)
      } else {
        this.modelForm.remindRuleVoList[index].userWithTrgNode = this.modelForm.remindRuleVoList[index].userWithTrgNode.filter(user => user.groupName != item.name)
      }
    },
    receiveTypeChange(val, index) {
      this.modelForm.remindRuleVoList[index].receivers = ''
      this.modelForm.remindRuleVoList[index].receiverList = []
      this.modelForm.remindRuleVoList[index].userWithTrgNode = []
    },
    hideFun() {
      this.$parent.hide()
    },
    getDetail() {
      if (this.id) {
        this.initLoading = true
        ruleConfigApi.getDetail2({id: this.id}).then(res => {
            if (res.data.code == 200) {
              let result = res.data.data
              let temp = {}
              Object.keys(this.modelForm).forEach(key => {
                  temp[key] = result[key]
              })
              for (const key in temp.remindRuleVoList) {
                if (Object.hasOwnProperty.call(temp.remindRuleVoList, key)) {
                  const element = temp.remindRuleVoList[key];
                  // 增加一个数据来源字段，用来在编辑页面判断是否要显示一些必要信息和操作按钮
                  element.source = 'database'
                  element.reportYear = element.reportTime ? new Date(element.reportTime).Format('yyyy') : ''
                  element.reportQuarter = ''
                  if (temp.reportName == '数字化转型专项实施方案任务表' && element.reportTime && element.reportTime.split('-')[1]) {
                    element.reportQuarter = element.reportTime.split('-')[1]
                  }
                  delete element.reportTime
                  if (element.itsReceiverGroupVoList) {
                    if (element.itsReceiverGroupVoList.length <= 0) {
                      element.receiverList = [{
                        id: '',
                        name: element.receiverNames,
                      }]
                    } else {
                      element.userWithTrgNode = []
                      element.receiverList = element.itsReceiverGroupVoList.map(item => {
                        let cssList = item.ccs ? item.ccs.split(',') : []
                        let receiverList = item.receiver ? item.receiver.split(',') : []
                        element.userWithTrgNode =[...element.userWithTrgNode, ...this.userGetTrgNode([...cssList, ...receiverList], item.groupName)] 
                        return {
                          name: item.groupName,
                          id: item.id
                        }
                      })
                    }
                  } else {
                    element.receiverList = element.receivers.split(',').map(item => {
                      return {
                        name: item,
                        id: item
                      }
                    })
                    element.userWithTrgNode = []
                  }
                  element.receiveWayArr = (''+element.receiveWay).split(',')
                  element.triggerDate = element.triggerTime
                  element.scheduledDate = element.scheduledTime
                }
              }
              this.modelForm = temp
              this.modelForm.reportNameCopy = this.modelForm.reportName
              this.$nextTick(() => {
                this.initLoading = false
              })
            }
        }).finally(() => {
          this.pageLoading = false
        })
      }
    },
    selectAddress(index) {
       new this.$pageModal(
        this.modelForm.remindRuleVoList[index].receiveType == RECEIVE_TYPE_PERSON ? SeleceAddressDatas : selectGroupByTable,
          {
          props: {
              /* menuId: menu.id */
              title: this.modelForm.remindRuleVoList[index].receiveType == RECEIVE_TYPE_PERSON ? "选择收件人" : "选择收件人组",
          }
          },
          (data) => {
            if (data && data.length) {
              if (this.modelForm.remindRuleVoList[index].receiveType == RECEIVE_TYPE_PERSON) {
                data.forEach(item => {
                  if (!this.modelForm.remindRuleVoList[index].receiverList.find(user => user.id == item.name)) {
                    this.modelForm.remindRuleVoList[index].receiverList.push({
                      name: item.name,
                      id: item.name
                    })
                  }
                })
                this.modelForm.remindRuleVoList[index].userWithTrgNode = []
              } else {
                data.forEach(item => {
                  if (!this.modelForm.remindRuleVoList[index].receiverList.find(user => user.id == item.id)) {
                    this.modelForm.remindRuleVoList[index].receiverList.push({
                      id: item.id,
                      name: item.groupName
                    })
                  }
                  let ccsList = item.ccs ? item.ccs.split(',') : []
                  let receiverList = item.receiver ? item.receiver.split(',') : []
                  let userTrgList = this.userGetTrgNode([...ccsList, ...receiverList], item.groupName)
                  this.modelForm.remindRuleVoList[index].userWithTrgNode = [...this.modelForm.remindRuleVoList[index].userWithTrgNode, ...userTrgList]
                })
                this.replaceContent(index)
              }
              let nameList = this.modelForm.remindRuleVoList[index].receiverList.map(item => item.id)
              this.modelForm.remindRuleVoList[index].receivers = nameList.length ? nameList.join(',') : ''

            }
          }
      )
    },
    isSameTrg(useList) {
      let flag = true
      for(var i = 0 ; i < useList.length ; i++){
        if(useList[i].nodeId != useList[0].nodeId){
          flag = false
          break;
        }
      }
      return flag
    },
    replaceContent(index) {
      if (this.modelForm.remindRuleVoList[index].context && !this.isSameTrg(this.modelForm.remindRuleVoList[index].userWithTrgNode)) {
        if ((this.modelForm.remindRuleVoList[index].context.includes('{BU}，') || this.modelForm.remindRuleVoList[index].context.includes('{BU}'))) {
          this.$Message.error({
            content: '所选收件人组内含多个业务单元，邮件内容中{BU}变量将不再生效',
            duration: 3
          })
        }
        this.modelForm.remindRuleVoList[index].context = this.modelForm.remindRuleVoList[index].context.replace(/({BU}，)|({BU})/g,'')
      }
    },
    userGetTrgNode(useList, groupName = null) {
      let list = []
      useList.forEach(item => {
        let selectUser = this.allUser.find(trgUser => {
          let users = trgUser.adminlist.split(',')
          return users.find(user => user == item)

        })
        list.push({
          name: item,
          nodeId: selectUser.nodeId,
          groupName: groupName
        })
      })
      return list
    },
    changeTriggerTime(date, index) {
      this.modelForm.remindRuleVoList[index].triggerTime = date
    },
    changeTime(date, key, index) {
      this.modelForm.remindRuleVoList[index][key] = date
    },
    changeReceiveWay(data, index) {
      this.$set(this.modelForm.remindRuleVoList[index], 'receiveWay', data.join(','))
    },
    init() {},
    _editRuleGroup(params) {
      ruleConfigApi.editInfo2(params).then(res => {
        this.createLoadding = false
        if (res.data.code == 200) {
          let msg = ''
          if (params.optType == ACTION_BUTTON_SAVE) {
            msg = '保存成功'
          } else if(params.optType == ACTION_BUTTON_SAVE_AND_SUBMIT) {
            msg = '提交成功'
          }
          this.$Message.success({
            content: msg,
            duration: 3
          })
          this.$emit('Close', true)
        }
      }).catch(e => {
        this.createLoadding = false
        this.$Message.success({
          content: e,
          duration: 3
        })
      })
    },
    editRuleConfigConfirm(data) {
      new this.$pageModal(
        editRuleConfigConfirm,
        {
          props: {
            data
          }
        },
        (data) => {
          if (!data) {
            this.createLoadding = false
            return
          }
          this._editRuleGroup(data)
        }
      );
    },
    save(actionButton) {
      this.createLoadding = true
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          let params = JSON.parse(JSON.stringify(this.modelForm))
          if (actionButton == 'save') {
            params.optType = ACTION_BUTTON_SAVE
          } else if (actionButton == 'saveAndSubmit') {
            params.optType = ACTION_BUTTON_SAVE_AND_SUBMIT
          }
          let contentTipFlag = false
          for (const key in params.remindRuleVoList) {
            if (Object.hasOwnProperty.call(params.remindRuleVoList, key)) {
              const element = params.remindRuleVoList[key]
              element.reportName = params.reportName
              element.reportType = params.reportType
              if (element.triggerCondition != TRIGGER_CONDITION_NOT_DELAY) {
                element.reportTime = new Date(element.reportYear).Format('yyyy')
                if (params.reportName == '数字化转型专项实施方案任务表') {
                  element.reportTime = element.reportTime + '-' + element.reportQuarter
                }
                delete element.reportYear
                delete element.reportQuarter
              }
              element.receiveWay = element.receiveWayArr.join(',')
              if ((element.context.includes('{BU}，') || element.context.includes('{BU}')) && !this.isSameTrg(element.userWithTrgNode) && element.receiveType != RECEIVE_TYPE_PERSON) {
                element.context = element.context.replace(/({BU}，)|({BU})/g,'')
                contentTipFlag = true
              }
              delete element.receiveWayArr
              delete element.receiverList
              delete element.userWithTrgNode
            }
          }
          if (contentTipFlag) {
            this.$Message.error({
              content: '所选收件人组内含多个业务单元，邮件内容中{BU}变量将不再生效',
              duration: 3
            })
          }
          delete params.reportNameCopy
          if (this.action == 'edit') {
            // 校验规则组
            let ruleList = params.remindRuleVoList.map((item, index) => {
              return {
                ruleName: '规则' + (index + 1),
                triggerTime: item.triggerTime,
              }
            })
            ruleConfigApi.checkRuleGroup(
              ruleList
            ).then(res => {
              if (res.data.code == 200 && res.data.data) {
                let msg = res.data.data
                if (actionButton == 'save') {
                  msg = msg.replace(/提交/g, '保存')
                } else if (actionButton == 'saveAndSubmit') {
                  msg = msg.replace(/保存/g, '提交')
                }
                this.$confirm({
                  title: '',
                  content: msg
                }).then(()=>{
                  if (actionButton == 'save') {
                    this.editRuleConfigConfirm(params)
                  } else if (actionButton == 'saveAndSubmit') {
                    this._editRuleGroup(params)
                  }
                }).catch(() => {
                  this.createLoadding = false
                })
              } else {
                this._editRuleGroup(params)
              }
            })
          } else {
            ruleConfigApi.createInfo2(params).then(res => {
              this.createLoadding = false
              if (res.data.code == 200) {
                let msg = ''
                if (params.optType == ACTION_BUTTON_SAVE) {
                  msg = '保存成功'
                } else if(params.optType == ACTION_BUTTON_SAVE_AND_SUBMIT) {
                  msg = '提交成功'
                }
                this.$Message.success({
                  content: msg,
                  duration: 3
                })
                this.$emit('Close', true)
              }
            }).catch(e => {
              this.createLoadding = false
              this.$Message.success({
                content: e,
                duration: 3
              })
            })
          }
        } else {
          this.createLoadding = false
          this.$Message.error({
            content: '请完善表单信息',
            duration: 3
          })
          return 0
        }
      })
    }
  },
  directives: {}
}
</script>

<style lang="less" scoped>
/deep/.ivu-btn-warning {
  padding: 4px 23px;
  background-color: #ff6f4b;
  border-color: #ff6f4b;
  border-radius: 0;
}
.Selecequarters {
  display:flex;
  /deep/.ivu-form-item-content{
      margin-left: -446px;
  }
  /deep/.ivu-form-item-content{
        margin-left: 2px;
        width: 800px;
  }
}
.plan-edit-box {
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .plan-page-header {
    display: flex;
    justify-content: space-between;
    height: 60px;
    align-items: center;
    padding: 0 20px;
    .header-title {
      font-size: 16px;
      font-weight: bold;
    }
  }
  .plan-page-content {
    flex: 1;
    overflow-y: scroll;
    overflow-x: hidden;
    padding: 0 5%;
  }
}
.addresee {
  position: relative;
  .button {
    position: absolute;
    right: -100px;
    top: 0;
  }
}
.user-list {
  width: 100%;
  min-height: 32px;
  border: 1px solid #d8d8d8;
  padding: 2px 10px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  .user{
    height: 26px;
    line-height: 26px;
    background: #f5f5f5;
    padding: 0 10px;
    border-radius: 5px;
    margin: 3px 5px;
    .user-name {
      margin-right: 4px;
    }
    .ivu-icon-ios-close {
      font-size: 18px;
      cursor: pointer;
    }
  }
}
</style>
